<?php

	namespace app\data\controller\shop;

	use app\data\controller\api\Sendsms;
	use app\data\model\NotarialOffice;
	use app\data\model\DataUser;
	use app\data\model\NotarizedMattersModel;
	use app\data\model\NotarizedTypeModel;
	use app\data\model\ShopOrder;

// use app\data\model\NotarizedMatters as NotarizedMattersModel;
	use app\data\service\OrderService;
	use app\data\service\PaymentService;
use app\data\service\QysService;
use app\data\service\TencentSerice;
	use app\data\service\UserAdminService;
	use Exception;
	use think\admin\Controller;
	use think\admin\extend\CodeExtend;
	use think\admin\model\SystemUser;
	use think\exception\HttpResponseException;
	use think\validate\ValidateRule;
	use WeMini\Scheme;

	/**
	 * 订单数据管理
	 * Class Order
	 * @package app\data\controller\shop
	 */
	class Order extends Controller
	{
		/**
		 * 支付方式
		 * @var array
		 */
		protected $payments = [];

		/**
		 * 控制器初始化
		 */
		protected function initialize()
		{
			parent::initialize();
			$this->payments = PaymentService::getTypeAll();
			// echo phpinfo();die;
		}

		/**
		 * 订单数据管理
		 * @auth true
		 * @menu true
		 * @throws \think\db\exception\DataNotFoundException
		 * @throws \think\db\exception\DbException
		 * @throws \think\db\exception\ModelNotFoundException
		 */
		public function index()
		{
			$this->title = '订单数据管理';
			$user = $this->app->session->get('user');
			$user_id = $user['id'];
			$authorize = trim($user['authorize'], ',');

			// 状态数据统计
			$this->total = ['t0' => 0, 't1' => 0, 't2' => 0,'tb' => 0, 't3' => 0, 't4' => 0, 't5' => 0, 't6' => 0, 'ta' => 0];
			$map = '1=1';
			// 公证员被匹配的订单
			if (!empty($authorize)) {
				//审批人
				if ($authorize == '2') {
					$map = "(approval_user_id = $user_id)";
				} //公证员
				else {
					$map = "(system_user_id = $user_id or system_user_id = 0) ";
				}

			}
			$this->user_id = $user_id;
			// halt(ShopOrder::mk()->field('status,count(1) total')->whereRaw($map)->group('status')->cursor());
			foreach (ShopOrder::mk()->field('status,payment_status,count(1) total')->whereRaw($map)->group('status,payment_status')->cursor() as $vo) {
				//待支付
				if ($vo['status'] == '3' && $vo['payment_status'] == '0'){
					[$this->total["tb"] = $vo['total'], $this->total["ta"] += $vo['total']];
				}
				//待认证
				else if($vo['status'] == '3' && $vo['payment_status'] == '1'){
					[$this->total["t{$vo['status']}"] = $vo['total'], $this->total["ta"] += $vo['total']];
				}else{
					[$this->total["t{$vo['status']}"] = $vo['total'], $this->total["ta"] += $vo['total']];
				}

			}
			// 订单列表查询
			$query = ShopOrder::mQuery();
			$query->like('order_no');
			$user_keys = input('user_keys', 0);
			if ($user_keys) {
				$query->whereLike('client_name|client_phone', '%' . $user_keys . '%');
			}
			$query->equal('status,payment_type,payment_status')->dateBetween('create_at,payment_datetime,cancel_datetime,truck_datetime,truck_send_datetime');

			// 列表选项卡
			if (($this->type = trim(input('type', 'ta'), 't'))) {
				$where_map = [];
				if ($this->type == 'b'){
					$where_map['status'] = 3;
					$where_map['payment_status'] = 0;
				}else if ($this->type == '3'){
					$where_map['status'] = 3;
					$where_map['payment_status'] = 1;
				}else{
					$where_map['status'] = $this->type;
				}
				if ($this->type != 'a'){
					$query->where($where_map);
				}
			}
			$query->append(['notarial_office_name', 'type_text', 'matter_name', 'sys_name', 'approval_name']);
			// 分页排序处理
			$query->where(['deleted_status' => 0])->whereRaw($map)->order('id desc')->page();
		}

		/**
		 * 订单列表处理
		 * @param array $data
		 * @throws \think\db\exception\DataNotFoundException
		 * @throws \think\db\exception\DbException
		 * @throws \think\db\exception\ModelNotFoundException
		 */
		protected function _index_page_filter(array &$data)
		{
//        UserAdminService::buildByUid($data);
//        UserAdminService::buildByUid($data, 'puid1', 'from');
//        OrderService::buildData($data);
//        foreach ($data as &$vo) {
//            if (!is_null($vo['payment_type']) and '' != $vo['payment_type']) {
//                $vo['payment_name'] = PaymentService::name($vo['payment_type']);
//            }
//        }
		}

		/**
		 * 编辑订单
		 * @auth true
		 */
		public function audit()
		{
			$user = $this->app->session->get('user');
			// 公证员只能查看所属公证处的公证事项
			if (empty($user['notarial_office_id'])) {
				$where = "1=1";
			} else {
				$where = "id=" . $user['notarial_office_id'];
			}
			$where = "1=1";
			//公证处
			$Offices = NotarialOffice::mk()->where($where)->where(['deleted' => 0])->select();
			$this->Offices = $Offices;
			if ($this->request->isGet()) {
				$this->type = input('get.type');
				// var_dump($this->type);die;
				$field = 'qys_document_list,id,unified_numbering,notarial_office_id,base_type,matter_id,other,trustee_id_card,client_house_purchase_agreement,client_property_information';
				$append = ['type_text', 'matter_name', 'notarial_office_name', 'other_image', 'trustee_id_card_image', 'client_house_purchase_agreement_image', 'client_property_information_image'];
				$this->matter = ShopOrder::field($field)->append($append)->where('id', input('get.id'))->find()->toArray();
				$this->assign('client_all_list', QysService::checkClientrNum($this->matter));
				$pdf_all_list =  json_decode($this->matter['qys_document_list'],true);
				if($pdf_all_list == null){
					$pdf_all_list= [];
				}
				$this->assign('pdf_all_list',$pdf_all_list);
				// foreach($pdf_all_list as $key=>$value){

				// }
				// var_dump($pdf_all_list);exit;
				// echo json_encode($this->matter);die;
				ShopOrder::mForm('', 'id');
			} else {
				$base_type = input('base_type');
				$video_forensics = input('video_forensics');
				$proxy_statement = input('proxy_statement');
				$read_agreement1 = input('read_agreement1');
				$read_agreement2 = input('read_agreement2');
				$read_agreement3 = input('read_agreement3');
				$read_agreement4 = input('read_agreement4');
				$read_agreement5 = input('read_agreement5');
				// $data = $this->_vali([
				//     'order_no.require' => '订单单号不能为空！',
				//     'status.in:0,1'    => '审核状态数值异常！',
				//     'status.require'   => '审核状态不能为空！',
				//     'reason_for_rejection.default'   => '',
				//     'type.require'     => '审核类型不能为空!',
				//     'step.default'     => '', //操作步骤(审核失败的情况下,跳到指定步骤)
				//     'approval_name.default'       => '',
				// ]);
				$data = input();

				if (isset($data['parents_household_register']))
					$data['parents_household_register'] = str_replace("|", ",", $data['parents_household_register']);
				//委托人购房协议
				if (isset($data['client_house_purchase_agreement']))
					$data['client_house_purchase_agreement'] = str_replace("|", ",", $data['client_house_purchase_agreement']);
				//委托人房产信息
				if (isset($data['client_property_information']))
					$data['client_property_information'] = str_replace("|", ",", $data['client_property_information']);
				//委托人户口本
				if (isset($data['client_household_register']))
					$data['client_household_register'] = str_replace("|", ",", $data['client_household_register']);
				//结婚证
				if (isset($data['client_marriage_certificate']))
					$data['client_marriage_certificate'] = str_replace("|", ",", $data['client_marriage_certificate']);
				//离婚证
				if (isset($data['client_divorce_certificate']))
					$data['client_divorce_certificate'] = str_replace("|", ",", $data['client_divorce_certificate']);
				if (isset($data['other']))
					$data['other'] = str_replace("|", ",", $data['other']);
				//关系证明
				if (isset($data['proof_of_relationship']))
					$data['proof_of_relationship'] = str_replace("|", ",", $data['proof_of_relationship']);
				//房产证
				if (isset($data['client_property_ownership_certificate']))
					$data['client_property_ownership_certificate'] = str_replace("|", ",", $data['client_property_ownership_certificate']);
				//信息确认
				if ($data['type'] == 1) {
					//驳回
					// if ($data['status']==0) $data['status'] = 2;
					//通过
					// 待支付
					// if ($data['status']==1){
					// $data['status'] = 3;
					// $data['payment_status'] = 0;
					//视频取证
					if (empty($video_forensics)) {
						$data['video_forensics'] = 0;
					} else {
						$data['video_forensics'] = 1;
					}
					if ($base_type == 0) {
						if (empty($proxy_statement)) $this->error('委托书不能为空！');
						$data['proxy_statement'] = $proxy_statement;
					}

					if (empty($read_agreement1)) $this->error('送达回证不能为空！');
					if (empty($read_agreement2)) $this->error('询问记录不能为空！');
					if (empty($read_agreement3)) $this->error('涉外民事类公证告知书不能为空！');
					if (empty($read_agreement4)) $this->error('公证受理通知单回执不能为空！');
					if (empty($read_agreement5)) $this->error('公证处公证申请表不能为空！');
					$data['read_agreement1'] = $read_agreement1;
					$data['read_agreement2'] = $read_agreement2;
					$data['read_agreement3'] = $read_agreement3;
					$data['read_agreement4'] = $read_agreement4;
					$data['read_agreement5'] = $read_agreement5;
					// }
				} //认证审核
				elseif ($data['type'] == 4) {
					// if ($data['status']==0) $data['status'] = 6;
					// if ($data['status']==1) $data['status'] = 5;
				} //审批人审核
				elseif ($data['type'] == 5) {
					// if ($data['status']==0) $data['status'] = 2;
					// if ($data['status']==1) {
					//     $data['status'] = 8;
					// }
				} //审批人审核
				else {
					// if ($data['status']==1) $data['status'] = 8;
					// 审核失败
					if ($data['status'] == 0) {
						// if ($data['step']==0) $data['status'] = 1;
						// if ($data['step']==1) $data['status'] = 4;
					}
				}

				// 更新订单支付状态
				$map = ['id' => input('id'), 'order_no' => $data['order_no']];
				$main_data = ShopOrder::mk()->strict(false)->where($map)->find();
				/**
				 * 处理契约锁文档
				 */
				$qyDoculist = QysService::mkDbDocumentList($data);
			
				$data['qys_document_list'] = $qyDoculist ;

				// 委托人json
				$client_json = json_decode($main_data['client_json'], true);
				//被编辑的序号
				$k = $main_data['client_num'];
				$client_json[$k]['full_name'] = $data['client_name'];
				$client_json[$k]['phone_number'] = $data['client_phone'];
				$client_json[$k]['idCard_z'] = $data['client_front_of_id_card'];
				$client_json[$k]['idCard_f'] = $data['client_reverse_side_of_id_card'];
				$client_json[$k]['household_files'] = explode(',', $data['client_household_register']);
				$image_src = [];
				$image_src['idCard_z'] = $data['client_front_of_id_card'];
				$image_src['idCard_f'] = $data['client_reverse_side_of_id_card'];
				$image_src['household_files'] = explode(',', $data['client_household_register']);
				$data['client_json'] = json_encode($client_json);
				$client_json[$k]['image_src'] = $image_src;


				if (isset($data['trustee_id_card_z'])) {
					// 受托人json  trustee_id_card
					$trustee_id_card = [];
					$trusteemsgArray = [];
					foreach ($data['trustee_id_card_z'] as $k => $v) {
						$trustee_id_card[$k]['idCard_z'] = $v;
						// 调取身份证识别方法
						$id_card_info = TencentSerice::distinguish($v);
						$trusteemsgArray[$k]['client_name'] = $id_card_info['Name'];//身份证号
						$trusteemsgArray[$k]['client_id_number'] = $id_card_info['IdNum'];//身份证号
						$trusteemsgArray[$k]['client_birthday'] = $id_card_info['Birth'];//出生日期
						$trusteemsgArray[$k]['client_sex'] = $id_card_info['Sex'];
					}
					foreach ($data['trustee_id_card_f'] as $k => $v) {
						$trustee_id_card[$k]['idCard_f'] = $v;
					}
					$data['trustee_id_card'] = json_encode($trustee_id_card);
					$data['trustee_msg'] = json_encode($trusteemsgArray);
				}

				//修改 对应id的主数据
				// ShopOrder::mk()->strict(false)->where($map)->update($data);
				//信息确认
				// if ($data['type']==1){
				//     $map = ['unified_numbering'=>$main_data['unified_numbering']];
				// }else{
				//     $map = ['id' => input('id'), 'order_no' => $data['order_no']];
				// }


				//修改同一组的其他数据 (多认委托)
				$data['approval_flag'] = 1;
				if ($data['base_type'] == 0) {
					//修改 对应id的主数据
					ShopOrder::mk()->strict(false)->where($map)->update($data);
					unset($data['id']);
					unset($data['client_name']);
					unset($data['client_phone']);
					unset($data['client_front_of_id_card']);
					unset($data['client_reverse_side_of_id_card']);
					unset($data['client_household_register']);
					$map = ['unified_numbering' => $main_data['unified_numbering']];
					if (ShopOrder::mk()->strict(false)->where($map)->update($data) !== false) {
						$this->success('操作成功！');
					} else {
						$this->error('订单审核失败！');
					}
				} else {
					if (ShopOrder::mk()->strict(false)->where($map)->update($data) !== false) {
						$this->success('操作成功！');
					} else {
						$this->error('订单审核失败！');
					}
				}


			}
		}

		//提交审核
		public function approval_user()
		{
			//审批人
			// authorize
			// whereRaw('FIND_IN_SET('.$hobby.',hobby_id)');
			$id = input("id");
			$this->id = $id;
			$authorize = 2;
			$approval_user = SystemUser::mk()->whereRaw('FIND_IN_SET(' . $authorize . ',authorize)')->where(['is_deleted' => 0, 'status' => 1])->select();
			$this->approval_user = $approval_user;
			if ($this->request->isGet()) {
				ShopOrder::mForm('', 'id');
			} else {
				$data = $this->_vali([
					'approval_user_id.require' => '审批人不能为空！',
				]);
				ShopOrder::mSave($data);
				$this->success('操作成功！');
			}
		}

		/**
		 * 审核订单
		 * @auth true
		 */
		public function approval_order()
		{
			$info = '驳回成功';
			$id = input("id");
			ShopOrder::mk()->where(['id' => $id])->update(['approval_user_id' => 0]);
			$this->success($info);
		}

		/**
		 * 下载二维码
		 * @auth true
		 */
		public function getQrcode()
		{
			$id = input("id");
			$url_link = getwxlink($id);
			$this->success('成功！', $url_link);
		}

		

		public function status()
		{
			try {
				$id = input("id");
				$status = input("status");
				if($status == '3'){
					$result = QysService::mkQysSend($id);
				}
			} catch (Exception $exception) {
	            $this->error($exception->getMessage());
	        }
			if($status == '3'){
				$message = '';
				if (isset($result[2]['message']) ) {
					$message =$result[2]['message'];
				} 
				if($result[0]!=1){
					$this->error('生成契约失败--请检查模版内容是否匹配 契约锁错误说明：--'.$message );
				}
			}
			
			ShopOrder::mk()->where(['id'=>$id])->update(['status'=>$status]);
			if ($status == '2' ){
				$order =  ShopOrder::field('*')->where('id', $id)->find()->toArray();
				$list = QysService::checkClientrNum($order);
				foreach($list as $key=>$value){
					ShopOrder::mk()->where(['id'=>$value['id']])->update(['qys_callback_status'=>0,'qys_callback_info'=>'']);
				}
				
			}

			//信息确认 3 进入支付状态 4
			try {
                if ($status == '3' || $status == '4'){
					// 调用接口 发送短信提示 创建 URL-Link
					$appid = sysconf('wechat.appid');
					$secret = sysconf('wechat.appsecret');
					$options = [
						'appid'=>$appid,
						'appsecret'=>$secret
					];
					$url_link = getwxlink($id,1);
				
					//获取变量
					$res = substr($url_link, strripos($url_link, "?t=") + 3);
					//发送短信
					$m = new Sendsms();
	
					$client_phone = ShopOrder::mk()->where(['id'=>$id])->value('client_phone');
					$phone = $client_phone;
					$SecretId = sysconf('vx.secretId');
					$SecretKey = sysconf('vx.secretKey');
					if($status == '3'){
						$templateid = '1625712';
					}else{
						$templateid = '1625712';
					}
					$post_data = [
						$res
					];
					$rt = $m->Sms_status($phone, $SecretId, $SecretKey,$templateid,$post_data);
				}
	        } catch (HttpResponseException $exception) {
	            
	        } catch (Exception $exception) {
	            
	        }
				// if ($status == '3' || $status == '4'){
				// 	// 调用接口 发送短信提示 创建 URL-Link
				// 	$appid = sysconf('wechat.appid');
				// 	$secret = sysconf('wechat.appsecret');
				// 	$options = [
				// 		'appid'=>$appid,
				// 		'appsecret'=>$secret
				// 	];
				// 	$url_link = getwxlink($id,1);
				//
				// 	//获取变量
				// 	$res = substr($url_link, strripos($url_link, "?t=") + 3);
				// 	//发送短信
				// 	$m = new Sendsms();
				//
				// 	$client_phone = ShopOrder::mk()->where(['id'=>$id])->value('client_phone');
				// 	$phone = $client_phone;
				// 	$SecretId = sysconf('vx.secretId');
				// 	$SecretKey = sysconf('vx.secretKey');
				// 	if($status == '3'){
				// 		$templateid = '1625712';
				// 	}else{
				// 		$templateid = '1625712';
				// 	}
				// 	$post_data = [
				// 		$res
				// 	];
				// 	$rt = $m->Sms_status($phone, $SecretId, $SecretKey,$templateid,$post_data);
				//
				// }

			ShopOrder::mSave($this->_vali([
				'status.in:1,2,3,4,5,6,7,8' => '状态值范围异常！',
				'status.require' => '状态值不能为空！',
			]), 'id');

		}

		/**
		 * 受理订单
		 * @auth true
		 */
		public function accept()
		{
			$status = input('status');
			$info = '';
			if ($status == '1') {
				$user_id = session('user')['id'];
				$info = '受理成功';
			} else {
				$user_id = 0;
				$info = '退回成功';
			}
			$id = input("id");
			ShopOrder::mk()->where(['id' => $id])->update(['system_user_id' => $user_id]);
			$this->success($info);
		}

		// /**
		//  * 编辑订单
		//  * @auth true
		//  */
		public function edit()
		{
			$this->matter = ShopOrder::field('base_type,matter_id')->append(['type_text', 'matter_name'])->where('id', input('get.id'))->find();
			ShopOrder::mForm('form');
		}

		/**
		 * 添加订单
		 * @auth true
		 */
		public function add()
		{
			ShopOrder::mForm('form');
		}

		/**
		 * 查看订单
		 * @auth true
		 */
		public function details()
		{
			$field = 'notarial_office_id,base_type,matter_id,other,trustee_id_card,client_house_purchase_agreement,client_property_information
			,unified_numbering,proxy_statement,contractId
			';
			$append = ['type_text', 'matter_name', 'notarial_office_name', 'other_image', 'trustee_id_card_image', 'client_house_purchase_agreement_image', 'client_property_information_image'];
			$this->matter = ShopOrder::field($field)->append($append)->where('id', input('get.id'))->find();
			if($this->matter->contractId != 0){
				$result = QysService::downPdfByOrderId($this->matter);
				$this->assign('docunmentListPath', $result[2]);
				ShopOrder::mForm('details_qys');
			}else{
				ShopOrder::mForm('details');
			}
		}

		protected function _details_form_filter(&$data){
			// halt($data);
			$data['video_src'] = json_decode($data['video_src'],true)??[];
			$unified_numbering = $data['unified_numbering'];
            $proxy_statement = $data['proxy_statement'];
			$order = ShopOrder::field('id,client_name,client_sex,client_birthday,client_id_number,create_at,trustee_msg')->where('unified_numbering',$unified_numbering)->select()->toArray();
			$user = [];
            // 'client_name':'李四',
            // 'client_sex':'男',
            // 'client_birthday':'1997年8月25日',
            // 'client_id_number':'211322199409191531',
            //受托人数组
            $user_s = [];
			foreach ($order as $k=>$v) {
                // $text = '委托人：'.$v['client_name'].'，男，1998年1月1日，身份证号：220382199801011234';
                $user[] = [
                    'client_name'=>$v['client_name'],
                    'client_sex'=>$v['client_sex'],
                    'client_birthday'=>date("Y年m月d日",strtotime($v['client_birthday'])),
                    'client_id_number'=>$v['client_id_number'],
                ];
                if ($k == 0){
                    $trustee_msg = json_decode($v['trustee_msg'],true);
                    if (!empty($trustee_msg)){
                        foreach($trustee_msg as $key => $value){
                            $trustee_msg[$key]['client_birthday'] = date("Y年m月d日",strtotime($trustee_msg[$key]['client_birthday']));
                        }

                        $user_s = $trustee_msg;
                    }
                }
            }

			$create_at = $order[0]['create_at'];

            //需要签名
            $handwritten_signature = '';

            $handwritten_signature = $data['handwritten_signature'];

            $data['proxy']['create_at'] = date("Y年m月d日",strtotime($create_at));;
            $data['proxy']['user'] = $user;
            $data['proxy']['user_s'] = $user_s;
            $data['proxy']['sign_img_src'] = $handwritten_signature;
            $data['proxy']['proxy_type'] = $data['proxy_type'];
            $data['proxy']['proxy_title'] = $data['proxy_title'];
            $data['proxy']['html'] = $proxy_statement;

		}

		/**
		 * 公证事项表单处理
		 * @param array $data
		 * @throws \think\db\exception\DataNotFoundException
		 * @throws \think\db\exception\ModelNotFoundException
		 * @throws \think\exception\DbException
		 */
		protected function _form_filter(&$data)
		{
			if ($this->request->isGet()) {
				$user = $this->app->session->get('user');
				// 公证员只能查看所属公证处的公证事项
				if (empty($user['notarial_office_id'])) {
					$where = "1=1";
				} else {
					$where = "id=" . $user['notarial_office_id'];
				}
				//公证处
				$Offices = NotarialOffice::mk()->where($where)->where(['deleted' => 0])->select();
				$this->Offices = $Offices;

				$this->cates = NotarizedMattersModel::field('id,name')->select()->toArray();
				if (isset($data['client_divorce_agreement'])) {
					$data['client_divorce_agreement'] = explode(',', $data['client_divorce_agreement']);
				} else {
					$data['client_divorce_agreement'] = [];
				}
				// if (isset($data['other'])){
				//     $data['other'] = explode(',',$data['other']);
				// }else{
				//     $data['other'] = [];
				// }
				// //购房协议
				// if (isset($data['client_house_purchase_agreement'])){
				//     $data['client_house_purchase_agreement'] = explode(',',$data['client_house_purchase_agreement']);
				// }else{
				//     $data['client_house_purchase_agreement'] = [];
				// }
				// //房产信息查询（产调）
				// // var_dump($data['client_house_purchase_agreement']);die;
				// if (isset($data['client_property_information'])){
				//     $data['client_property_information'] = explode(',',$data['client_property_information']);
				// }else{
				//     $data['client_property_information'] = [];
				// }
				//受托人 trustee_id_card
				if (isset($data['trustee_id_card'])) {
					$data['trustee_id_card'] = json_decode($data['trustee_id_card'], true);
				} else {
					$data['trustee_id_card'] = [];
				}

				//父母户口本
				if (isset($data['parents_household_register']))
					$data['parents_household_register'] = str_replace(",", "|", $data['parents_household_register']);
				//委托人购房协议
				if (isset($data['client_house_purchase_agreement']))
					$data['client_house_purchase_agreement'] = str_replace(",", "|", $data['client_house_purchase_agreement']);
				//委托人房产信息
				if (isset($data['client_property_information']))
					$data['client_property_information'] = str_replace(",", "|", $data['client_property_information']);
				//委托人户口本
				if (isset($data['client_household_register']))
					$data['client_household_register'] = str_replace(",", "|", $data['client_household_register']);
				//结婚证
				if (isset($data['client_marriage_certificate']))
					$data['client_marriage_certificate'] = str_replace(",", "|", $data['client_marriage_certificate']);
				//离婚证
				if (isset($data['client_divorce_certificate']))
					$data['client_divorce_certificate'] = str_replace(",", "|", $data['client_divorce_certificate']);
				if (isset($data['other']))
					$data['other'] = str_replace(",", "|", $data['other']);
				//关系证明
				if (isset($data['proof_of_relationship']))
					$data['proof_of_relationship'] = str_replace(",", "|", $data['proof_of_relationship']);
				//房产证
				if (isset($data['client_property_ownership_certificate']))
					$data['client_property_ownership_certificate'] = str_replace(",", "|", $data['client_property_ownership_certificate']);
				// echo json_encode($data);die;
			} else {


				$data['unified_numbering'] = OrderService::setOrderNo(); //统一编号
				// echo json_encode($data);die;
				// 订单实际金额
				// $notarizedMattersInfo = NotarizedMattersModel::field('id,name,initial_amount,continued_amount')->where('id', $data['matter_id'])->find();//公证事项信息
				// 委托类型(0委托公证,1出生公证,2亲属关系公证)
				$notarizedMattersInfo = NotarizedMattersModel::field('id,name,initial_amount,continued_amount')
					->where('notarial_office_id', $data['notarial_office_id'])
					->where('type', $data['base_type'])
					->find();//公证事项信息
				if ($data['number_goods'] > 1) {
					$data['amount_real'] = $notarizedMattersInfo['initial_amount'] + ($data['number_goods'] - 1) * $notarizedMattersInfo['continued_amount'];
				} else {

					$data['amount_real'] = $notarizedMattersInfo['initial_amount']; //订单实际金额
				}
				// 获取公证员信息
				$user = $this->app->session->get('user');
				// $data['notarial_office_id'] = $user['notarial_office_id']; //公证处id
				$data['system_user_id'] = $user['id']; //公证员id
				// 后台创建订单,状态为待认证
				// $data['status'] = 3;
				// 后台创建订单 要修改价格
				$data['status'] = 1;
				$addArray = [];


				// ************************************************************都要用|分割******************************************************************************?
				//父母户口本
				if (isset($data['parents_household_register']))
					$data['parents_household_register'] = str_replace("|", ",", $data['parents_household_register']);
				//委托人购房协议
				if (isset($data['client_house_purchase_agreement']))
					$data['client_house_purchase_agreement'] = str_replace("|", ",", $data['client_house_purchase_agreement']);
				//委托人房产信息
				if (isset($data['client_property_information']))
					$data['client_property_information'] = str_replace("|", ",", $data['client_property_information']);
				//委托人户口本
				if (isset($data['client_household_register']))
					$data['client_household_register'] = str_replace("|", ",", $data['client_household_register']);
				//结婚证
				if (isset($data['client_marriage_certificate']))
					$data['client_marriage_certificate'] = str_replace("|", ",", $data['client_marriage_certificate']);
				//离婚证
				if (isset($data['client_divorce_certificate']))
					$data['client_divorce_certificate'] = str_replace("|", ",", $data['client_divorce_certificate']);
				if (isset($data['other']))
					$data['other'] = str_replace("|", ",", $data['other']);
				//关系证明
				if (isset($data['proof_of_relationship']))
					$data['proof_of_relationship'] = str_replace("|", ",", $data['proof_of_relationship']);
				if (isset($data['client_property_ownership_certificate']))
					$data['client_property_ownership_certificate'] = str_replace("|", ",", $data['client_property_ownership_certificate']);
				// ******************************************************************************************************************************************?
				//委托人
				foreach ($data['client_name'] as $k => $v) {
					if ($k == 0) {
						$addArray[$k]['is_creater'] = 1;
					} else {
						$addArray[$k]['is_creater'] = 0;
					}
					$addArray[$k]['client_num'] = $k;
					$addArray[$k]['client_name'] = $v;
					$addArray[$k]['client_phone'] = $data['client_phone'][$k];
					$addArray[$k]['client_front_of_id_card'] = $data['client_front_of_id_card'][$k];

					// 调取身份证识别方法
					$id_card_info = TencentSerice::distinguish($data['client_front_of_id_card'][$k]);
					$addArray[$k]['client_id_number'] = $id_card_info['IdNum'];//身份证号
					$addArray[$k]['client_birthday'] = $id_card_info['Birth'];//出生日期
					$addArray[$k]['client_sex'] = $id_card_info['Sex'];


					$addArray[$k]['client_reverse_side_of_id_card'] = $data['client_reverse_side_of_id_card'][$k];
					$addArray[$k]['client_household_register'] = $data['client_household_register'][$k];
					$addArray[$k]['order_no'] = OrderService::setOrderNo(); //订单号
				}

				//调取身份证识别方法
				//代理人信息


				$base_type = $data['base_type'];
				//委托公正
				if ($base_type == 0) {
					// 委托人json
					$client_json = [];
					foreach ($data['client_name'] as $k => $v) {
						$client_json[$k]['full_name'] = $v;
						$client_json[$k]['phone_number'] = $data['client_phone'][$k];
						$client_json[$k]['idCard_z'] = $data['client_front_of_id_card'][$k];
						$client_json[$k]['idCard_f'] = $data['client_reverse_side_of_id_card'][$k];
						$client_json[$k]['household_files'] = explode(',', $data['client_household_register'][$k]);
						$image_src = [];
						$image_src['idCard_z'] = $data['client_front_of_id_card'][$k];
						$image_src['idCard_f'] = $data['client_reverse_side_of_id_card'][$k];
						$image_src['household_files'] = array(explode(',', $data['client_household_register'][$k]));
						$client_json[$k]['image_src'] = $image_src;
					}
					$data['client_json'] = json_encode($client_json);
					// 受托人json  trustee_id_card
					$trustee_id_card = [];
					$trusteemsgArray = [];

					if (isset($data['trustee_id_card_z'])) {
						foreach ($data['trustee_id_card_z'] as $k => $v) {
							$trustee_id_card[$k]['idCard_z'] = $v;
							if ($v != '') {
								// 调取身份证识别方法
								$id_card_info = TencentSerice::distinguish($v);
								$trusteemsgArray[$k]['client_name'] = $id_card_info['Name'];//身份证号
								$trusteemsgArray[$k]['client_id_number'] = $id_card_info['IdNum'];//身份证号
								$trusteemsgArray[$k]['client_birthday'] = $id_card_info['Birth'];//出生日期
								$trusteemsgArray[$k]['client_sex'] = $id_card_info['Sex'];
							}
						}
						foreach ($data['trustee_id_card_f'] as $k => $v) {
							$trustee_id_card[$k]['idCard_f'] = $v;
						}
						$data['trustee_id_card'] = json_encode($trustee_id_card);
						$data['trustee_msg'] = json_encode($trusteemsgArray);
					}
					unset($data['trustee_id_card_z']);
					unset($data['trustee_id_card_f']);
				}
				unset($data['client_name']);
				unset($data['client_phone']);
				unset($data['client_front_of_id_card']);
				unset($data['client_reverse_side_of_id_card']);
				unset($data['client_household_register']);
				// echo count($addArray);die;
				foreach ($addArray as $v) {
					$arr[] = array_merge($v, $data);
				}
				if (ShopOrder::mk()->saveAll($arr)) {
					$this->success('订单添加成功', "javascript:history.back()");
				} else {
					$this->error('订单添加失败', 'javascript:history.back()');
				}
			}
		}

		/*
		 * 二级联动
		 */
		public function linkage()
		{
			$data = input('');
			$user = $this->app->session->get('user');
			$authorize = trim($user['authorize'], ',');
			// 公证员只能查看所属公证处的公证事项

			if (!empty($authorize)) {
				$where[] = ['notarial_office_id', '=', $user['notarial_office_id']];
			}
			if ($data['matter'] == 0) {
				// $notarial_office_id = $data['notarial_office_id'];
				// $where = "notarial_office_id=$notarial_office_id";
				// $list = NotarizedTypeModel::mk()->field('id,name')->where($where)->select()->toArray();
				$list = [];
			} else {
				$list = [
					[
						'id' => 1,
						'name' => '本人办理',
					],
					[
						'id' => 2,
						'name' => '代理人办理',
					]
				];
				// $where[] = ['type','=',$data['matter']];
				// $list = NotarizedMattersModel::field('id,name')->where($where)->select()->toArray();
			}

			return json($list);
		}

		/**
		 * 删除订单数据
		 * @auth true
		 */
		public function remove()
		{
			ShopOrder::mDelete();
		}

		/**
		 * 修改订单金额
		 * @auth true
		 */
		public function update_amount_real()
		{
			ShopOrder::mSave($this->_vali([
				'amount_real.require' => '金额不能为空！',
			]), 'id');
		}
	}